package com.jcw.controller;

import cn.hutool.core.lang.UUID;
import com.jcw.common.R;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;

@Slf4j
@RestController
@RequestMapping("/common")
public class CommonController {

    @Value("${reggie.Path}")
    private String path;

    @GetMapping("/download")
    public void download(String name, HttpServletResponse response){
        FileInputStream inputStream;
        ServletOutputStream outputStream;
        try {
            //创建一个输入流，读取文件内容
            inputStream = new FileInputStream(path+name);
            outputStream = response.getOutputStream();
            int len;
            byte[] bytes = new byte[1024];
            while ((len = inputStream.read(bytes)) != -1) {
                outputStream.write(bytes,0, len);
                outputStream.flush();
            }
            inputStream.close();
            outputStream.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @PostMapping("/upload")
    public R<String> upload(MultipartFile file) {
        String fileName;
        try {
            //生成一个uuid，给图片重新赋值名字
            UUID uuid = UUID.randomUUID(true);
            //获取图片的原信息
            String originalFilename = file.getOriginalFilename();
            //截取原信息中有用的数据，即后缀名
            String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
            //将文件要存放的路径，生成的文件名，还有后缀组成一个完整的文件地址
            fileName = uuid + suffix;
            //用来查看文件目录是否存在
            File dir = new File(path);
            if (!dir.exists()){
                //创建目录
                dir.createNewFile();
            }
            //将文件转存到硬盘指定的位置上
            file.transferTo(new File(path+fileName));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return R.success(fileName);
    }
}
